module.exports = {
  canvas,
}
var matchType = 1
function canvas(data) {
  let ctx = wx.createCanvasContext(data.canvasId);
  var systemInfo = wx.getSystemInfoSync();
  var windowWidth = systemInfo.windowWidth;
  var windowHeight = systemInfo.windowHeight;

  var screenWidth = systemInfo.screenWidth;
  var screenHeight = systemInfo.screenHeight;
  var pixelRatio = systemInfo.pixelRatio

  console.log(windowWidth, windowHeight, data)
  // 设置ctx到data
  data.ctx = ctx;
  // 设置响应转换
  data.getSize = (new UIToReality(windowWidth)).transitionUI;
  // 设置画布的宽高到data
  data.canvasWidth = data.getSize(750);
  // data.canvasHeight = data.getSize(900);
  // data.canvasWidth = data.getSize(windowWidth * 2)
  // console.error(windowHeight)
  // data.canvasHeight = data.getSize(windowHeight * 2)
  data.canvasHeight = windowHeight

  // 统一修改模块偏移值
  const P = 0.621
  var a = (windowWidth/windowHeight).toFixed(3)
  data.offsetHeight = (P - a) * 2100

  // 根据matchType调整每日和奖金池的位置
  data.day = { offsetLeft: 0 }
  data.line = { offsetLeft: 0 }
  data.award = { offsetLeft: 0 }
  if (data.data.matchType == matchType) {
    data.day.offsetLeft = 65
    data.line.offsetLeft = 749 / 2
    data.award.offsetLeft = -data.day.offsetLeft
  }

  // 画板改变
  if (data.changeSize) data.changeSize({
    width: data.canvasWidth,
    height: data.canvasHeight,
  });

  // 保存为图片
  this.canvasToTempFilePath = function(callback) {
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum'] === false) {
          wx.openSetting({})
        } else {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            height: data.canvasHeight - data.getSize(114),
            canvasId: data.canvasId,
            success: function (res) {
              if (callback) {
                callback(res.tempFilePath);
              } else {
                wx.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success(res) {
                    wx.showToast({
                      title: '保存成功',
                      duration: 1000
                    })
                  }
                })
              }
            }
          })
        }
      }
    })
  }
  this.canvasData=function(d){
    data.data = d;
    canvaQrcodeTips(data)
    // canvasTitle(data)
    drawBox1(data)
    drawBox2(data)
  }

  // 填充背景色及背景大小
  canvaBg(data);
}

// 绘制字体
function drawText(data, params) {
  var {title, x, y, fontSize, color = "#332F36",align = 'left'} = params
  var ctx = data.ctx
  ctx.setFillStyle(color)
  ctx.setFontSize(fontSize)
  if (align == 'center') {
    ctx.setTextAlign(align) 
    x = x / 2
  } else {
    ctx.setTextAlign(align)
  }
  if (!title) return
  ctx.fillText(title, x, y)
  ctx.draw(true)
  ctx.save()
  ctx.restore()
}

// 色块一
function drawBox1(data){
  // 绘制模块一
  var w = data.getSize(697)
  var h = data.getSize(318)
  var x = data.getSize(22)
  var y = data.getSize(545 + data.offsetHeight)
  var bg = '#FFF1EA'
  roundRect(data,x, y, w, h, 7, bg)

  // 设置文字样式字体大小为30的
  var fontSize = data.getSize(30)
  var params = {
    title: '我正在参与' + data.data.name + '挑战赛',
    x: data.getSize(64),
    y: data.getSize(600 + data.offsetHeight),
    fontSize,
  }
  drawText(data,params)
  
  var params = {
    title: '每日',
    x: data.getSize(126 + data.day.offsetLeft),
    y: data.getSize(710 + data.offsetHeight),
    fontSize,
  }
  drawText(data, params)

  var params = {
    title: '奖金池',
    x: data.getSize(531 + data.award.offsetLeft),
    y: data.getSize(710 + data.offsetHeight),
    fontSize,
  }
  drawText(data, params)

  // 文字字体大小为20的
  var fontSize = data.getSize(20)
  var params = {
    title: '高达',
    x: data.getSize(621 + data.award.offsetLeft),
    y: data.getSize(718 + data.offsetHeight),
    fontSize,
  }
  drawText(data, params)

  // 目标步数
  var fontSize = data.getSize(36)
  var params = {
    title: data.data.dayAim,
    x: data.getSize(100 + data.day.offsetLeft),
    y: data.getSize(770 + data.offsetHeight),
    fontSize,
  }
  drawText(data, params)

  var dayAim = String(data.data.dayAim)
  var stepOffsetLeft = 110 + 21 * dayAim.length + data.day.offsetLeft
  var fontSize = data.getSize(20)  
  var params = {
    title: '步',
    x: data.getSize(stepOffsetLeft),
    y: data.getSize(780 + data.offsetHeight),
    fontSize,
  }
  drawText(data, params)
  

  // 奖金池
  var params = {
    title: data.data.bonusPool,
    x: data.getSize(544 + data.award.offsetLeft),
    y: data.getSize(770 + data.offsetHeight),
    fontSize: data.getSize(36),
  }
  drawText(data, params)
  var bonusPool = String(data.data.bonusPool)
  var bonusPoolOffsetLeft = 554 + 20 * bonusPool.length
  var params = {
    title: '元',
    x: data.getSize(bonusPoolOffsetLeft + data.award.offsetLeft),
    y: data.getSize(780 + data.offsetHeight),
    fontSize: data.getSize(20),
  }
  drawText(data, params)

  // 修改文字样式
  // 绘制渐变直线
  var x = data.getSize(data.line.offsetLeft || 477)
  var y = data.getSize(696 + data.offsetHeight)
  var x1 = data.getSize(data.line.offsetLeft || 477)
  var y1 = data.getSize(677 + 138 + data.offsetHeight)
  _drawGradientLine(data,x, y, x1, y1)

  // matchType:1、官方，2、自建
  if (data.data.matchType == matchType) {
    return
  }
  var params = {
    title: '活动天数',
    x: data.getSize(315),
    y: data.getSize(710 + data.offsetHeight),
    fontSize: data.getSize(30),
  }
  drawText(data, params)

  var params = {
    title: data.data.customScheduleDays,
    x: data.getSize(330),
    y: data.getSize(770 + data.offsetHeight),
    fontSize: data.getSize(36),
  }
  drawText(data, params)
  var customScheduleDays = String(data.data.customScheduleDays)
  var dayOffsetLeft = 340 + 20 * customScheduleDays.length
  var params = {
    title: '天',
    x: data.getSize(dayOffsetLeft),
    y: data.getSize(780 + data.offsetHeight),
    fontSize: data.getSize(20)
  }
  drawText(data, params)

  // 绘制渐变直线
  var x = data.getSize(277)
  var y = data.getSize(696 + data.offsetHeight)
  var x1 = data.getSize(277)
  var y1 = data.getSize(677 + 138 + data.offsetHeight)
  _drawGradientLine(data, x, y, x1, y1)
}

// 绘制渐变线
function _drawGradientLine(data, x, y, x1, y1) {
  var ctx = data.ctx
  ctx.beginPath();
  ctx.moveTo(x, y);
  ctx.lineTo(x1, y1);
  var grd = ctx.createLinearGradient(x, y, x1, y1);
  grd.addColorStop(0, "#E5E5E5");
  grd.addColorStop(0.4, "#888888");
  grd.addColorStop(1, "#FFFFFF");
  ctx.lineWidth = 1;
  ctx.strokeStyle = grd;
  ctx.stroke();
  ctx.closePath();
}

// 绘制模块二
function drawBox2(data) {
  var w = data.getSize(697)
  var h = data.getSize(190)
  var x = data.getSize(22)
  var y = data.getSize(882 + data.offsetHeight)
  var bg = '#FFF1EA'
  roundRect(data,x, y, w, h, 7, bg)

  // 头像
  canvaImghead(data);
  // 昵称
  canvaNickname(data);
  canvaQrcodeImg(data)
  canvaQrcodeTips(data)
}

function _drawHead(data) {
  var ctx = data.ctx
  var w = data.getSize(100)
  var h = data.getSize(100)
  var x = data.getSize(113)
  var y = data.getSize(980)

  // this.ctx.fillStyle = 'red'
  // this.ctx.arc(x, y, w / 2, 0, 2 * Math.PI)
  // this.ctx.fill()
  // this.ctx.clip()

  if (!this.data.headimg) return
  ctx.drawImage(this.data.headimg, x - w / 2, y - h / 2, w, h)
  ctx.draw(true)
}

// 绘制二维码
function _drawQrcode(data) {
  var w = data.getSize(94)
  var h = data.getSize(94)
  var x = data.getSize(570)
  var y = data.getSize(955)

  if (!this.data.qrcode) return
  this.ctx.drawImage(this.data.qrcode, x - w / 2, y - h / 2, w, h)
  this.ctx.draw(true)
}

// 绘制Tips
function _drawTips(data) {
  var params = {
    title: '扫一扫报名参加',
    x: data.getSize(478),
    y: data.getSize(1046),
    fontSize: data.getSize(26),
  }
  drawText(data, params)
}


function roundRect(data,x, y, w, h, r, bg) {
  data.ctx.save();
  if (w < 2 * r) {
    r = w / 2;
  }
  if (h < 2 * r) {
    r = h / 2;
  }

  data.ctx.beginPath();
  data.ctx.setFillStyle(bg);
  data.ctx.setStrokeStyle(bg);
  data.ctx.setLineWidth(1);
  data.ctx.moveTo(x + r, y);
  data.ctx.arcTo(x + w, y, x + w, y + h, r);
  data.ctx.arcTo(x + w, y + h, x, y + h, r);
  data.ctx.arcTo(x, y + h, x, y, r);
  data.ctx.arcTo(x, y, x + w, y, r);
  data.ctx.fill();
  data.ctx.closePath();
  data.ctx.draw(true)
}


// 昵称
function canvasTitle(data) {
  var ctx = data.ctx;
  var tempData = {
    title: data.data.name,
    x: data.canvasWidth,
    y: data.getSize(40),
    fontSize: data.getSize(72),
    color: '#ffffff',
    align: 'center'
  }
  if (!tempData.title) return;
  drawText(data, tempData)

  var ctx = data.ctx;
  var tempData = {
    title: '挑战赛',
    x: data.canvasWidth,
    y: data.getSize(132),
    fontSize: data.getSize(72),
    color: '#ffffff',
    align: 'center'
  }
  if (!tempData.title) return;
  drawText(data, tempData)
}


// 昵称
function canvaNickname(data) {
  var ctx = data.ctx;
  var tempData = {
    nickName: data.data.username,
    marginLeft: data.getSize(184),
    marginTop: data.getSize(976 + data.offsetHeight),
    fontSize: data.getSize(26)
  }

  if (!tempData.nickName) return;

  // 字符串数组
  let arr = getFontsMetrics(data, tempData.nickName, 220);
  // 当前需要渲染几行
  let line = 1;
  for (let i = 0; i < arr.length; i++) {
    if (i < line) {
      let text = i == line - 1 ? arr[i].textd : arr[i].text;
      ctx.setTextAlign('left')
      ctx.setTextBaseline('top')
      ctx.setFillStyle('#332F36')
      ctx.setFontSize(tempData.fontSize)
      ctx.fillText(text, tempData.marginLeft, tempData.marginTop)
      ctx.draw(true, function () {
        console.log('呢称绘制完毕')
      })
      tempData.marginTop += data.getSize(40);
    }
  }
}

// 扫码提示
function canvaQrcodeTips(data) {
  var ctx = data.ctx;
  var tempData = {
    nickName: '扫一扫报名参加',
    marginLeft: data.getSize(528),
    marginTop: data.getSize(1026 + data.offsetHeight),
    fontSize: data.getSize(20)
  }

  if (!tempData.nickName) return;

  // 字符串数组
  let arr = getFontsMetrics(data, tempData.nickName, 220);
  // 当前需要渲染几行
  let line = 1;
  for (let i = 0; i < arr.length; i++) {
    if (i < line) {
      let text = i == line - 1 ? arr[i].textd : arr[i].text;
      ctx.setTextAlign('left')
      ctx.setTextBaseline('top')
      ctx.setFillStyle('#332F36')
      ctx.setFontSize(tempData.fontSize)
      ctx.fillText(text, tempData.marginLeft, tempData.marginTop)
      ctx.draw(true, function () {
        console.log('呢称绘制完毕')
      })
      tempData.marginTop += data.getSize(40);
    }
  }
}

// 二维码
function canvaQrcodeImg(data) {
  var ctx = data.ctx;
  var tempData = {
    headimg: data.data.qrCodeUrl,
    width: data.getSize(90),
    height: data.getSize(90),
    marginLeft: data.getSize(551),
    marginTop: data.getSize(916 + data.offsetHeight),
  }

  if (!tempData.headimg) return;

  ctx.save();
  // ctx.arc(tempData.width / 2 + tempData.marginLeft, tempData.height / 2 + tempData.marginTop, tempData.width / 2, 0, 2 * Math.PI)
  // ctx.fill()
  // ctx.clip()
  ctx.drawImage(tempData.headimg, tempData.marginLeft, tempData.marginTop, tempData.width, tempData.height)
  ctx.restore()
  ctx.draw(true, function () {
    console.log('头像绘制完毕')
  })
}

// 头像
function canvaImghead(data) {
  var ctx = data.ctx;
  var tempData = {
    headimg: data.data.headPortrait,
    width: data.getSize(100),
    height: data.getSize(100),
    marginLeft: data.getSize(64),
    marginTop: data.getSize(931 + data.offsetHeight),
  }

  if (!tempData.headimg) return;

  ctx.save();
  ctx.arc(tempData.width / 2 + tempData.marginLeft, tempData.height / 2 + tempData.marginTop, tempData.width / 2, 0, 2 * Math.PI)
  ctx.fill()
  ctx.clip()
  ctx.drawImage(tempData.headimg, tempData.marginLeft, tempData.marginTop, tempData.width, tempData.height)
  ctx.restore()
  ctx.draw(true, function () {
    console.log('头像绘制完毕')
  })
}

// 填充背景色及背景大小
function canvaBg(data) {
  var ctx = data.ctx;
  var transitionUI = data.transitionUI;
  var canvasWidth = data.canvasWidth;
  var canvasHeight = data.canvasHeight;
  var bgImg = './images/bg.png';

  if (!bgImg) return;

  // 填充背景颜色
  ctx.drawImage(bgImg, 0, 0, canvasWidth, canvasHeight)
  ctx.draw(true,function(){
    console.log('背景绘制完毕')
  })
}

/**
 * 对应字符串通过指定的长度分成多个数组
 * @param   data    Object
 * @param   value   String        需要截取的字符串
 * @param   width   Number        当前位置插入字符串的最长长度（响应式，单位：rpx）
 * @return          ObjectArray   返回字符串截取json
 */
function getFontsMetrics(data, value, width) {
  var ctx = data.ctx;
  let metrics = null,
    arr = [],
    temp = "";
  for (let i = 0; i < value.length; i++) {
    metrics = ctx.measureText(temp);
    if (metrics.width >= data.getSize(width)) {
      let textd = temp.slice(0, temp.length - 1) + "...";
      arr.push({
        text: temp,
        textd,
      });
      temp = value[i];
    } else {
      temp += value[i];
    }
    if (i == value.length - 1) {
      let textd = temp;

      if (ctx.measureText(temp).width > data.getSize(width)) {
        textd = temp.slice(0, temp.length - 1) + "...";
      }

      arr.push({
        text: temp,
        textd,
      });
    }
  }

  return arr;
}

// 响应式转换对象(ui750转实际px)
function UIToReality(windowWidth) {

  this.transitionUI = function(size = 750) {
    return size / 750 * windowWidth;
  }

}